package com.lsf.dunlian.utils.audio;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.google.gson.Gson;
import com.lsf.dunlian.BuildConfig;
import com.lsf.dunlian.R;
import com.lsf.dunlian.activity.AttendanceActivity;
import com.lsf.dunlian.config.PreferenceUtil;
import com.lsf.dunlian.config.Urls;
import com.lsf.dunlian.constant.Constant;
import com.lsf.dunlian.entity.AndroidVersionAddressVo;
import com.lsf.dunlian.entity.BaseEntity;
import com.lsf.dunlian.entity.UpdateApkEntity;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 10109 on 2017/12/18.
 */

public class UpdateApk implements Runnable{
    private Activity activity;
    private String urls;
    private String content;
    private File apkFile;
    private String newversion;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (newversion.equals("0")) {
                showUpdateDialog();
            }
        }
    };
    public  UpdateApk(Activity activity){
        this.activity=activity;
    }
    @Override
    public void run() {
        loadupdata();
    }

    public  String getSystemModel() {
        return Build.MODEL;
    }

    private void loadupdata(){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().get().url(Urls.UPDATE_APK
                + "?userId=" + PreferenceUtil.getSharedPreference(Constant.USERID)
                + "&version=" + BuildConfig.VERSION_NAME).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    UpdateApkEntity vo = new Gson().fromJson(result, UpdateApkEntity.class);
                    if (vo.code==200 && vo.data!=null && vo.data.size()>0) {
                        AndroidVersionAddressVo addressVo = vo.data.get(0);

                        urls =addressVo.address;
                        content =addressVo.content;
                        newversion = "0";
                        handler.sendEmptyMessage(0);
                    }
                }
            }
        });
    }


    @SuppressLint("NewApi")
    private void showUpdateDialog() {
        if (activity.isDestroyed())return;
        Dialog dialog = null;
        if (dialog==null){
            dialog=new Dialog(activity, R.style.Dialog);
            dialog.setCanceledOnTouchOutside(false);
            View view= LayoutInflater.from(activity).inflate(R.layout.updateui,null);
            TextView update= (TextView) view.findViewById(R.id.update);
            TextView str= (TextView) view.findViewById(R.id.str);
            str.setText(content);
            ProgressBar my_progress= (ProgressBar) view.findViewById(R.id.my_progress);
            update.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        downFile(urls,my_progress);
                    } else {
                        Toast.makeText(activity, "SD卡不可用，请插入SD卡", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            dialog.setContentView(view);
        }
        dialog.show();
    }
    void downFile(final String url,ProgressBar my_progress) {
        new Thread() {
            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(url);
                HttpResponse response;
                try {
                    response = client.execute(get);
                    HttpEntity entity = response.getEntity();
                    int length = (int) entity.getContentLength(); // 获取文件大小
                    my_progress.setMax(length); // 设置进度条的总长度
                    InputStream is = entity.getContent();
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        apkFile = new File(Environment.getExternalStorageDirectory(), "update.apk");
                        if (!apkFile.exists()){
                            apkFile.getParentFile().mkdirs();
                            apkFile.createNewFile();
                        }
                        fileOutputStream = new FileOutputStream(apkFile);
                        byte[] buf = new byte[64];
                        int ch = -1;
                        int process = 0;
                        while ((ch = is.read(buf)) != -1) {
                            fileOutputStream.write(buf, 0, ch);
                            process += ch;
                            my_progress.setProgress(process); // 这里就是关键的实时更新进度了！
                        }
                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    down();
                } catch (ClientProtocolException e) {
                    activity.runOnUiThread(() -> Toast.makeText(activity,e.getMessage(),Toast.LENGTH_LONG));
                } catch (IOException e) {
                    activity.runOnUiThread(() -> Toast.makeText(activity,e.getMessage(),Toast.LENGTH_LONG));
                }
            }

        }.start();
    }
    void down() {
        handler.post(() -> {
            update();
        });
    }
    void update() {
        try {
            Intent intent =new Intent(Intent.ACTION_VIEW);
            //判断是否是AndroidN以及更高的版本
            if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N) {
                Uri contentUri = FileProvider.getUriForFile(activity,"com.lsf.dunlian.fileProvider",new File(Environment.getExternalStorageDirectory(), "update.apk"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(contentUri,"application/vnd.android.package-archive");
            }else{
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "update.apk")),"application/vnd.android.package-archive");
            }
            activity.startActivity(intent);
        }catch (Exception e){
            activity.runOnUiThread(() -> Toast.makeText(activity,e.getMessage(),Toast.LENGTH_LONG));
        }
    }
}
